package com.itheima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.article.feign.ApAuthorFeign;
import com.itheima.article.pojo.ApAuthor;
import com.itheima.common.constants.BusinessConstants;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.vo.PageResultVo;
import com.itheima.common.vo.ResultVo;
import com.itheima.user.dto.ApUserRealnamePageRequestDto;
import com.itheima.user.mapper.ApUserMapper;
import com.itheima.user.pojo.ApUser;
import com.itheima.user.pojo.ApUserRealname;
import com.itheima.user.mapper.ApUserRealnameMapper;
import com.itheima.user.service.ApUserRealnameService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.wemedia.feign.WmUserFeign;
import com.itheima.wemedia.pojo.WmUser;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.invoke.LambdaConversionException;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * @description <p>APP实名认证信息 业务实现</p>
 *
 * @version 1.0
 * @package com.itheima.user.service.impl
 */
@Slf4j
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Autowired
    public ApUserMapper apUserMapper;

    @Autowired
    private WmUserFeign wmUserFeign;

    @Autowired
    private ApAuthorFeign apAuthorFeign;


    /**
     * 分页查询
     * @param dto
     * @return
     */
    @Override
    public PageResultVo pageList(ApUserRealnamePageRequestDto dto) {
        //1. 设置分页参数
        Page<ApUserRealname> pagea = new Page<>(dto.getPage(), dto.getSize());
        //2. 设置查询条件
        LambdaQueryWrapper<ApUserRealname> que = new LambdaQueryWrapper<>();
        que.eq(dto.getStatus()!=null,ApUserRealname::getStatus,dto.getStatus());
        //3. 查询
        page(pagea,que);

        return PageResultVo.pageResult(dto.getPage(),dto.getSize(),pagea.getTotal(),pagea.getRecords());
    }

    /**
     * 审核通过
     *
     * @param paramMap
     */
    @Override
    public void authpass(Map<String, Object> paramMap) {
        //1. 参数校验
        Integer id = (Integer) paramMap.get("id");
        log.debug("实名认证：id={}",id);
        //============= 实名认证信息表 =============
        //   状态的判断 通过id查询, 状态不为1，报错
        ApUserRealname apUserRealname = getById(id);
        if(null == apUserRealname || apUserRealname.getStatus() !=1){
            throw new LeadNewsException("状态不正确或数据不存在");
        }
        //   更新
        //     创建updatePojo
        ApUserRealname userRealname = new ApUserRealname();
        userRealname.setId(id.longValue());
        userRealname.setStatus(BusinessConstants.ApUserRealnameConstants.AUTH_PASS);
        userRealname.setUpdatedTime(LocalDateTime.now());
        //     执行更新
        updateById(userRealname);
        //================ 用户信息表 ===================
        Long userId = apUserRealname.getUserId();
        //    创建updatePojo
        ApUser apUser = new ApUser();
        //    设置id 为 上面查询到用户id
        apUser.setId(userId);
        //    flag, is_identity_authentication
        apUser.setFlag(BusinessConstants.ApUserConstants.FLAG_WEMEDIA);
        apUser.setIsIdentityAuthentication(BusinessConstants.ApUserConstants.AUTHENTICATED);
        apUserMapper.updateById(apUser);
        //===================自媒体微服 自媒体用户表===========
        //    远程调用
        //1. 远程调用 通过ap_user.id查询自媒体用户表
        ResultVo<WmUser> getByApUserId = wmUserFeign.getByApUserId(userId);
        if(!getByApUserId.isSuccess()){
            log.error("用户实名认证::远程调用自媒体查询失败:{},{}",apUser,getByApUserId.getErrorMessage());
            // 远程调用失败了
            throw new LeadNewsException("查询自媒体用户信息失败!");
        }
        //查询用户表信息
        ApUser apUserInfo = apUserMapper.selectById(apUser);
        //2. 如果不存在则 远程调用添加自媒体账号
        WmUser wmUser = getByApUserId.getData();
        if (null == wmUser){
            //远程调用添加自媒体账号
            wmUser = addWmUser(apUserInfo);
        }
        // 自媒体用户的id
        Long wmUserId = wmUser.getId();
        //==============文章微服中作者表====================
        //1. 远程调用 通过ap_user.id, 自媒体用户的id 查询文章微服作者表
        ResultVo<ApAuthor> getAuthorResult = apAuthorFeign.getByApUserIdAndWmUserId(userId, wmUserId);
        //1.1 解析结果
        if (!getAuthorResult.isSuccess()){
            log.error("用户实名认证::远程调用文章微服查询失败:{},{},{}",userId,wmUserId,getAuthorResult,getBaseMapper());
            // 远程调用失败了
            throw new LeadNewsException("查询作者信息失败!");
        }
        //2. 如果不存在，则远程调用添加作者
        ApAuthor author = getAuthorResult.getData();
        if (null == author){
            //则远程调用添加作者
            addAuthor(apUserInfo,wmUserId);
        }
    }



    /**
     * 审核 驳回
     *
     * @param paramMap
     */
    @Override
    public void authFail(Map<String, Object> paramMap) {
        //1. 获取参数
        Integer id = (Integer) paramMap.get("id");
        String msg = (String) paramMap.get("msg");
        //2. 创建更新的pojo
        ApUserRealname userRealname = new ApUserRealname();
        userRealname.setId(id.longValue());
        userRealname.setStatus(BusinessConstants.ApUserRealnameConstants.AUTH_REJECT);
        userRealname.setReason(msg);
        userRealname.setUpdatedTime(LocalDateTime.now());
        //3. 执行更新
        updateById(userRealname);

    }
    /**
     * 远程调用添加作者
     * @param apUserInfo
     * @param wmUserId
     */
    private void addAuthor(ApUser apUserInfo, Long wmUserId) {
        //1. 构建作者的pojo
        ApAuthor author = new ApAuthor();
        author.setWmUserId(wmUserId);
        author.setName(apUserInfo.getName());
        author.setUserId(apUserInfo.getId());
        author.setType(BusinessConstants.ApAuthorConstants.A_MEDIA_SELLER);
        author.setCreatedTime(LocalDateTime.now());
        //2. 远程调用添加作者
        ResultVo resultVo=apAuthorFeign.add(author);
        //3. 解析结果
        if (!resultVo.isSuccess()){
            log.error("用户实名认证::远程调用添加作者失败:{},{}",apUserInfo.getId(),wmUserId,resultVo.getErrorMessage());
            throw new LeadNewsException("添加作者失败!");
        }
    }

    /**
     * 远程调用添加自媒体账号
     * @param apUserInfo
     * @return
     */
    private WmUser addWmUser(ApUser apUserInfo) {
        //1. 构建自媒体账号信息
        WmUser pojo = new WmUser();
        Long apUserId = apUserInfo.getId();
        BeanUtils.copyProperties(apUserInfo,pojo);
        pojo.setId(null);
        pojo.setApUserId(apUserId);
        pojo.setNickname(apUserInfo.getName());
        pojo.setType(BusinessConstants.WmUserConstants.TYPE_PERSONAL);
        pojo.setStatus(BusinessConstants.WmUserConstants.STATUS_OK);
        pojo.setScore(0);
        pojo.setCreatedTime(LocalDateTime.now());
        //5. 远程调用添加自媒体账号
        ResultVo<WmUser> addResult = wmUserFeign.add(pojo);
        //6. 解析远程调用后的结果
        if (!addResult.isSuccess()){
            log.error("用户实名认证::远程调用自媒体添加账号失败:{},{}",apUserId,addResult.getErrorMessage());
            throw new LeadNewsException("添加自媒体账号失败!");
        }
        //7. 返回数据
        return addResult.getData();
    }
}
